package com.wlb.test.service.quartz.example;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.Trigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.DateBuilder.evenMinuteDate;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

/**
 * @Author:wanglibing
 * @Mail:1728891211@qq.com
 * @Date:Created in 9:10 2018/1/10
 * @Description:
 */
public class SimpleExample {
    public void run()throws Exception{
        Logger logger = LoggerFactory.getLogger(SimpleExample.class);
        logger.info("------- Initializing ----------------------");
        //定义调度器
        StdSchedulerFactory sf = new StdSchedulerFactory();
        Scheduler sc = sf.getScheduler();
        logger.info("------- Initialization Complete ----------------------");
        //获取当前时间的下一分钟
        Date date = evenMinuteDate(new Date());
        logger.info("------- Scheduling Job  -------------------");
        // 定义job
        // 在quartz中，有组的概念，组+job名称 唯一的
        JobDetail detail = newJob(HelloJob.class).withIdentity("job1", "group1").build();
        // 定义触发器，在下一分钟启动
        //Trigger trigger = newTrigger().withIdentity("trigger1", "group1").startAt(date).build();
        Trigger trigger = newTrigger().withIdentity("trigger1", "group1").withSchedule(cronSchedule("0/5 * * * * ?")).build();
        // 将job注册到调度器
        sc.scheduleJob(detail,trigger);
        logger.info(detail.getKey() + " will run at: " + date);
        sc.start();
        logger.info("------- Started Scheduler -----------------");

        // 等待65秒
        logger.info("------- Waiting 65 seconds... -------------");
        try {
            // wait 65 seconds to show job
            Thread.sleep(60L * 1000L);
            // executing...
        } catch (Exception e) {
            //
        }

        // 关闭调度器
        logger.info("------- Shutting Down ---------------------");
        sc.shutdown(true);
        logger.info("------- Shutdown Complete -----------------");
    }

    public static void main(String[] args) throws Exception {
        SimpleExample simpleExample = new SimpleExample();
        simpleExample.run();
    }
}
